package cn.ante.ymcc.exception;


import cn.ante.ymcc.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    //拦截异常 : 这个注解就可以拦截器 GlobleException 异常
    @ExceptionHandler(GlobalException.class)
    public JSONResult globalException(GlobalException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),e.getCode());
    }


    //拦截器其他异常
    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),"7000");
    }

    //拦截器其他异常
    @ExceptionHandler(RuntimeException.class)
    public JSONResult runTimeException(RuntimeException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),"6000");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult validateException(MethodArgumentNotValidException e){
        StringBuffer sb = new StringBuffer();
        for (ObjectError allError : e.getBindingResult().getAllErrors()) {
            sb.append(allError.getDefaultMessage()).append(",") ;
        }
        e.printStackTrace();
        return JSONResult.error(sb.toString(),"7000");
    }

}
